import React, { useState, useEffect, useMemo } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Trophy, TrendingUp, Target, Coins, Zap, Sword, Shield, Info, User, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Columns, Plus, GripVertical, RefreshCw, Play, Pause } from 'lucide-react'
// import { PlayerPerformanceStats, LeaguePlayerRanking as LeaguePlayerRankingType } from '@/types/dota'
import { useLeagueData } from '@/hooks/useLeagueData'

interface LeaguePlayerRankingProps {
  leagueId: number
}

type Dota2Position = 'all' | 1 | 2 | 3 | 4 | 5

const POSITIONS = [
  { id: 'all', name: '全部位置', description: '综合排名', icon: <Trophy className="w-4 h-4" /> },
  { id: 1, name: '1号位 (核心)', description: '后期大哥', icon: <Sword className="w-4 h-4" /> },
  { id: 2, name: '2号位 (中单)', description: '中路核心', icon: <Zap className="w-4 h-4" /> },
  { id: 3, name: '3号位 (劣势路)', description: '劣势路核心', icon: <Shield className="w-4 h-4" /> },
  { id: 4, name: '4号位 (软辅)', description: '游走辅助', icon: <Target className="w-4 h-4" /> },
  { id: 5, name: '5号位 (硬辅)', description: '保护辅助', icon: <User className="w-4 h-4" /> }
]

const LeaguePlayerRanking: React.FC<LeaguePlayerRankingProps> = ({ leagueId }) => {
  const { 
    leagueRanking, 
    loading, 
    error, 
    loadLeagueRanking,
    enableAutoUpdate,
    disableAutoUpdate,
    checkForUpdates,
    lastUpdateCheck,
    rankingProgress
  } = useLeagueData(leagueId)
  
  const [autoUpdateEnabled, setAutoUpdateEnabled] = useState(false)
  const [isCheckingUpdates, setIsCheckingUpdates] = useState(false)
  
  // 位置选择状态
  const [selectedPosition, setSelectedPosition] = useState<Dota2Position>('all')
  
  // 表格状态管理
  const [selectedRows, setSelectedRows] = useState<Set<number>>(new Set())
  const [currentPage, setCurrentPage] = useState(1)
  const [rowsPerPage, setRowsPerPage] = useState(10)
  const [visibleColumns, setVisibleColumns] = useState({
    rank: true,
    player: true,
    position: false, // 隐藏位置列
    matches: true,
    winRate: true,
    kda: true,
    gpm: true,
    xpm: true,
    positionScore: true,
    avgData: true,
    score: true
  })

  useEffect(() => {
    if (leagueId) {
      loadLeagueRanking()
    }
  }, [leagueId, loadLeagueRanking])

  // 为每个位置创建专门的评分算法
  const calculatePositionScore = (player: any, position: Dota2Position): number => {
    if (position === 'all') {
      // 全部位置时使用综合评分
      return player.final_score || player.raw_score || 0
    }
    
    const gpm = player.avg_gpm || 0
    const xpm = player.avg_xpm || 0
    const kills = player.avg_kills || 0
    const deaths = player.avg_deaths || 0
    const assists = player.avg_assists || 0
    const lastHits = player.avg_last_hits || 0
    const denies = player.avg_denies || 0
    const heroDamage = player.avg_hero_damage || 0
    const towerDamage = player.avg_tower_damage || 0
    const healing = player.avg_hero_healing || 0
    const wards = player.avg_obs_placed || 0
    const dewarding = player.avg_sen_placed || 0
    const kda = deaths > 0 ? (kills + assists) / deaths : kills + assists
    const killParticipation = player.avg_kill_participation || 0
    const crowdControl = player.avg_crowd_control_per_min || 0

    switch (position) {
      case 1: // 1号位 (Carry) - 注重经济、输出、推塔
        return (
          gpm * 0.3 +           // 经济能力 (30%)
          lastHits * 0.25 +     // 补刀能力 (25%)
          heroDamage * 0.0002 + // 英雄伤害 (20%)
          towerDamage * 0.001 + // 推塔伤害 (15%)
          kda * 50              // KDA (10%)
        )

      case 2: // 2号位 (Mid) - 注重伤害、击杀、经济
        return (
          heroDamage * 0.0003 + // 英雄伤害 (30%)
          gpm * 0.25 +          // 经济能力 (25%)
          kills * 80 +          // 击杀数 (20%)
          xpm * 0.15 +          // 经验获取 (15%)
          kda * 40              // KDA (10%)
        )

      case 3: // 3号位 (Offlaner) - 劣势路，注重团战贡献、承伤、控制
        return (
          // 团战参与率 - 最重要指标 (30%)
          killParticipation * 1000 +
          
          // 助攻数 - 团战贡献 (25%)
          assists * 70 +
          
          // 控制技能使用 - 团战控制 (20%)
          crowdControl * 150 +
          
          // 英雄伤害 - 输出贡献 (15%)
          heroDamage * 0.0003 +
          
          // 生存能力 - 适应性调整 (10%)
          (kda > 0.8 ? Math.min(kda * 50, 200) : 0) +
          
          // 推塔伤害 - 边路推进 (额外加分)
          towerDamage * 0.001
        )

      case 4: // 4号位 (Support) - 注重助攻、视野、团队贡献
        return (
          assists * 80 +        // 助攻数 (30%)
          wards * 100 +         // 插眼数 (25%)
          healing * 0.01 +      // 治疗量 (20%)
          dewarding * 80 +      // 反眼数 (15%)
          (kda > 1.5 ? kda * 40 : 0) // 生存能力 (10%)
        )

      case 5: // 5号位 (Hard Support) - 注重视野、治疗、牺牲精神
        return (
          wards * 120 +         // 插眼数 (35%)
          healing * 0.015 +     // 治疗量 (30%)
          assists * 70 +        // 助攻数 (20%)
          dewarding * 100 +     // 反眼数 (10%)
          (deaths < 8 ? (8 - deaths) * 20 : 0) // 生存奖励 (5%)
        )

      default:
        return 0
    }
  }

  // 根据位置评分算法对所有玩家进行排名
  const getFilteredAndSortedPlayers = useMemo(() => {
    if (!leagueRanking?.players) return []

    // 对所有玩家计算选定位置的评分
    const playersWithScore = leagueRanking.players.map(player => {
      const positionScore = selectedPosition === 'all' 
        ? player.final_score || player.raw_score || 0
        : calculatePositionScore(player, selectedPosition)
      
      return {
        ...player,
        positionScore
      }
    })

    // 按位置评分排序（所有玩家都参与排名）
    playersWithScore.sort((a, b) => b.positionScore - a.positionScore)

    // 重新分配排名
    return playersWithScore.map((player, index) => ({
      ...player,
      positionRank: index + 1
    }))
  }, [leagueRanking, selectedPosition])

  // 手动检查更新
  const handleCheckUpdates = async () => {
    setIsCheckingUpdates(true)
    try {
      await checkForUpdates()
    } finally {
      setIsCheckingUpdates(false)
    }
  }

  // 切换自动更新
  const handleToggleAutoUpdate = () => {
    if (autoUpdateEnabled) {
      disableAutoUpdate()
      setAutoUpdateEnabled(false)
    } else {
      enableAutoUpdate(10 * 60 * 1000) // 10分钟间隔
      setAutoUpdateEnabled(true)
    }
  }

  // 格式化最后更新检查时间
  const formatLastUpdateCheck = (timestamp?: number) => {
    if (!timestamp) return '从未检查'
    const now = Date.now()
    const diff = now - timestamp
    const minutes = Math.floor(diff / (1000 * 60))
    
    if (minutes < 1) return '刚刚检查'
    if (minutes < 60) return `${minutes}分钟前`
    const hours = Math.floor(minutes / 60)
    if (hours < 24) return `${hours}小时前`
    const days = Math.floor(hours / 24)
    return `${days}天前`
  }

  const getRankBadgeColor = (rank: number) => {
    if (rank === 1) return 'bg-yellow-500 text-white'
    if (rank === 2) return 'bg-gray-400 text-white'
    if (rank === 3) return 'bg-amber-600 text-white'
    if (rank <= 10) return 'bg-blue-500 text-white'
    return 'bg-gray-200 text-gray-700'
  }

  const getRankIcon = (rank: number) => {
    if (rank <= 3) return <Trophy className="w-4 h-4" />
    return null
  }

  const formatNumber = (num: number | undefined, decimals: number = 1) => {
    if (num === undefined || num === null || isNaN(num)) {
      return 0
    }
    return Number(num.toFixed(decimals))
  }

  const formatPercentage = (num: number) => {
    return `${(num * 100).toFixed(1)}%`
  }

  // 辅助函数
  const handleSelectAll = (checked: boolean) => {
    if (checked && getFilteredAndSortedPlayers.length > 0) {
      const allIds = new Set(getFilteredAndSortedPlayers.map(player => player.account_id))
      setSelectedRows(allIds)
    } else {
      setSelectedRows(new Set())
    }
  }

  const handleSelectRow = (accountId: number, checked: boolean) => {
    const newSelected = new Set(selectedRows)
    if (checked) {
      newSelected.add(accountId)
    } else {
      newSelected.delete(accountId)
    }
    setSelectedRows(newSelected)
  }

  const getPaginatedData = () => {
    const startIndex = (currentPage - 1) * rowsPerPage
    const endIndex = startIndex + rowsPerPage
    return getFilteredAndSortedPlayers.slice(startIndex, endIndex)
  }

  const getTotalPages = () => {
    return Math.ceil(getFilteredAndSortedPlayers.length / rowsPerPage)
  }

  // 重置分页当位置改变时
  useEffect(() => {
    setCurrentPage(1)
    setSelectedRows(new Set())
  }, [selectedPosition])

  if (loading.ranking) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="w-5 h-5" />
            玩家表现排名
          </CardTitle>
        </CardHeader>
        <CardContent>
          {rankingProgress.total > 0 ? (
            <div className="space-y-4">
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-2">{rankingProgress.message}</p>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300" 
                    style={{ width: `${(rankingProgress.current / rankingProgress.total) * 100}%` }}
                  ></div>
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  {rankingProgress.current} / {rankingProgress.total} ({Math.round((rankingProgress.current / rankingProgress.total) * 100)}%)
                </p>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-4">{rankingProgress.message || '正在加载...'}</p>
              </div>
              {[...Array(10)].map((_, i) => (
                <div key={i} className="flex items-center space-x-4">
                  <Skeleton className="w-8 h-8 rounded-full" />
                  <div className="flex-1">
                    <Skeleton className="h-4 w-32 mb-2" />
                    <Skeleton className="h-3 w-48" />
                  </div>
                  <Skeleton className="w-16 h-6" />
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    )
  }

  if (error.ranking) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="w-5 h-5" />
            玩家表现排名
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <p className="text-red-500 mb-4">{error.ranking}</p>
            <button 
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              重试
            </button>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!leagueRanking || leagueRanking.players.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="w-5 h-5" />
            玩家表现排名
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <p className="text-gray-500">暂无玩家数据</p>
          </div>
        </CardContent>
      </Card>
    )
  }

  const currentPositionInfo = POSITIONS.find(p => p.id === selectedPosition) || POSITIONS[0]

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="w-5 h-5" />
            选手表现排名
            {/* 算法说明图标 */}
            <div className="relative group">
              <Info className="w-4 h-4 text-gray-400 hover:text-blue-500 cursor-help" />
              {/* 悬停提示 */}
              <div className="absolute left-0 top-6 w-96 p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50">
                <h4 className="font-semibold text-sm mb-3 text-gray-800 dark:text-gray-200">位置评分算法说明</h4>
                <div className="text-xs text-gray-600 dark:text-gray-300 space-y-2">
                  <div className="border-b pb-2 mb-2 border-gray-200 dark:border-gray-600">
                    <h5 className="font-medium text-gray-700 dark:text-gray-300 mb-1">位置检测</h5>
                    <p className="text-xs">基于GPM、XPM、KDA、补刀、伤害、治疗、插眼等数据自动识别玩家主要位置</p>
                  </div>
                  <div className="space-y-1">
                    <div><strong>1号位 (核心):</strong> 重视经济发育(GPM×1.5)、补刀(×3)、后期输出</div>
                    <div><strong>2号位 (中单):</strong> 重视等级优势(XPM×1.4)、击杀能力(×120)、参战率</div>
                    <div><strong>3号位 (劣势路):</strong> 重视团战参与率(×1000)、控制技能(×150)、助攻贡献、生存适应</div>
                    <div><strong>4号位 (软辅):</strong> 重视助攻(×100)、视野控制(插眼×150)、游走支援</div>
                    <div><strong>5号位 (硬辅):</strong> 重视保护能力、视野控制(插眼×200)、牺牲精神</div>
                  </div>
                </div>
              </div>
            </div>
          </CardTitle>
        </div>
        <div className="flex items-center gap-4">
          {/* 位置选择下拉菜单 */}
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">位置筛选:</span>
            <Select value={selectedPosition.toString()} onValueChange={(value) => {
              const newPosition = value === 'all' ? 'all' : parseInt(value) as Dota2Position
              setSelectedPosition(newPosition)
            }}>
              <SelectTrigger className="w-48">
                <SelectValue>
                  <div className="flex items-center gap-2">
                    {currentPositionInfo.icon}
                    <span>{currentPositionInfo.name}</span>
                  </div>
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {POSITIONS.map((position) => (
                  <SelectItem key={position.id} value={position.id.toString()}>
                    <div className="flex items-center gap-2">
                      {position.icon}
                      <div>
                        <div className="font-medium">{position.name}</div>
                        <div className="text-xs text-muted-foreground">{position.description}</div>
                      </div>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          {/* 增量更新控制面板 */}
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            {lastUpdateCheck && (
              <span>上次检查: {formatLastUpdateCheck(lastUpdateCheck)}</span>
            )}
            <Button
              variant="outline"
              size="sm"
              onClick={handleCheckUpdates}
              disabled={isCheckingUpdates}
              className="h-8"
            >
              {isCheckingUpdates ? (
                <>
                  <RefreshCw className="w-3 h-3 mr-1 animate-spin" />
                  检查中
                </>
              ) : (
                <>
                  <RefreshCw className="w-3 h-3 mr-1" />
                  检查更新
                </>
              )}
            </Button>
            <Button
              variant={autoUpdateEnabled ? "default" : "outline"}
              size="sm"
              onClick={handleToggleAutoUpdate}
              className="h-8"
            >
              {autoUpdateEnabled ? (
                <>
                  <Pause className="w-3 h-3 mr-1" />
                  停止自动更新
                </>
              ) : (
                <>
                  <Play className="w-3 h-3 mr-1" />
                  启用自动更新
                </>
              )}
            </Button>
          </div>
        </div>
        <p className="text-sm text-muted-foreground">
          {selectedPosition === 'all' 
            ? `共 ${leagueRanking.total_players} 名玩家`
            : `${currentPositionInfo.name} • 共 ${getFilteredAndSortedPlayers.length} 名玩家`
          } • 最少参加4场比赛 • 更新时间: {new Date(leagueRanking.last_updated).toLocaleString()}
        </p>
      </CardHeader>
      <CardContent>
        <div className="overflow-hidden rounded-lg border">
          <div className="relative w-full overflow-x-auto">
            <Table>
              <TableHeader className="bg-muted sticky top-0 z-10">
                <TableRow>
                  {/* 拖拽手柄 */}
                  <TableHead className="w-8"></TableHead>
                  
                  {/* 全选复选框 */}
                  <TableHead className="w-8">
                    <div className="flex items-center justify-center">
                      <Checkbox
                        checked={selectedRows.size === getFilteredAndSortedPlayers.length && getFilteredAndSortedPlayers.length > 0}
                        onCheckedChange={handleSelectAll}
                        aria-label="Select all"
                      />
                    </div>
                  </TableHead>

                  {visibleColumns.rank && <TableHead className="w-[60px]">排名</TableHead>}
                  {visibleColumns.player && <TableHead>玩家</TableHead>}
                  {visibleColumns.position && <TableHead className="text-center">位置</TableHead>}
                  {visibleColumns.matches && <TableHead className="text-center hidden sm:table-cell">比赛</TableHead>}
                  {visibleColumns.winRate && <TableHead className="text-center">胜率</TableHead>}
                  {visibleColumns.kda && <TableHead className="text-center hidden md:table-cell">KDA</TableHead>}
                  {visibleColumns.gpm && <TableHead className="text-center hidden lg:table-cell">GPM</TableHead>}
                  {visibleColumns.xpm && <TableHead className="text-center hidden lg:table-cell">XPM</TableHead>}
                  {visibleColumns.positionScore && <TableHead className="text-center hidden xl:table-cell">位置评分</TableHead>}
                  {visibleColumns.avgData && <TableHead className="text-center hidden xl:table-cell">平均数据</TableHead>}
                  {visibleColumns.score && <TableHead className="text-right">最终评分</TableHead>}
                </TableRow>
              </TableHeader>
              <TableBody>
                {getPaginatedData().map((player) => (
                  <TableRow key={player.account_id} className="hover:bg-muted/50">
                    {/* 拖拽手柄 */}
                    <TableCell>
                      <Button variant="ghost" size="sm" className="h-7 w-7 p-0">
                        <GripVertical className="h-3 w-3 text-muted-foreground" />
                        <span className="sr-only">Drag to reorder</span>
                      </Button>
                    </TableCell>

                    {/* 行选择复选框 */}
                    <TableCell>
                      <div className="flex items-center justify-center">
                        <Checkbox
                          checked={selectedRows.has(player.account_id)}
                          onCheckedChange={(checked) => handleSelectRow(player.account_id, checked as boolean)}
                          aria-label="Select row"
                        />
                      </div>
                    </TableCell>

                    {/* 排名 */}
                    {visibleColumns.rank && (
                      <TableCell>
                        <Badge className={`${getRankBadgeColor(player.positionRank)} flex items-center gap-1 w-fit`}>
                          {getRankIcon(player.positionRank)}
                          <span className="hidden sm:inline">#{player.positionRank}</span>
                          <span className="sm:hidden">{player.positionRank}</span>
                        </Badge>
                      </TableCell>
                    )}

                    {/* 玩家信息 */}
                    {visibleColumns.player && (
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 bg-muted rounded-full flex items-center justify-center">
                            <User className="w-4 h-4 text-muted-foreground" />
                          </div>
                          <div className="min-w-0">
                            <div className="font-medium truncate">{player.personaname}</div>
                            <div className="text-sm text-muted-foreground sm:hidden">
                              {player.matches_played}场 • {formatPercentage(player.win_rate)}
                            </div>
                            <div className="text-xs text-muted-foreground hidden sm:block">ID: {player.account_id}</div>
                          </div>
                        </div>
                      </TableCell>
                    )}

                    {/* 位置 */}
                    {visibleColumns.position && (
                      <TableCell className="text-center">
                        <Badge className="bg-gray-100 text-gray-800 flex items-center gap-1 w-fit mx-auto">
                          <Trophy className="w-4 h-4" />
                          <span>
                            {selectedPosition === 'all' ? '全部' : `${selectedPosition}号位`}
                          </span>
                        </Badge>
                      </TableCell>
                    )}

                    {/* 比赛场数 - 隐藏在小屏幕 */}
                    {visibleColumns.matches && (
                      <TableCell className="text-center hidden sm:table-cell">
                        <Badge variant="outline" className="text-xs">
                          {player.matches_played}
                        </Badge>
                      </TableCell>
                    )}

                    {/* 胜率 */}
                    {visibleColumns.winRate && (
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-1">
                          <Target className="w-3 h-3 text-muted-foreground hidden sm:block" />
                          <span className="font-medium">{formatPercentage(player.win_rate)}</span>
                        </div>
                        {/* 移动端显示额外信息 */}
                        <div className="text-xs text-muted-foreground md:hidden mt-1">
                          KDA: {formatNumber(player.avg_kda)}
                        </div>
                      </TableCell>
                    )}

                    {/* KDA - 隐藏在中等屏幕以下 */}
                    {visibleColumns.kda && (
                      <TableCell className="text-center hidden md:table-cell">
                        <div className="flex items-center justify-center gap-1">
                          <Sword className="w-3 h-3 text-muted-foreground" />
                          <span className="font-medium">{formatNumber(player.avg_kda)}</span>
                        </div>
                      </TableCell>
                    )}

                    {/* GPM - 隐藏在大屏幕以下 */}
                    {visibleColumns.gpm && (
                      <TableCell className="text-center hidden lg:table-cell">
                        <div className="flex items-center justify-center gap-1">
                          <Coins className="w-3 h-3 text-muted-foreground" />
                          <span className="font-medium">{formatNumber(player.avg_gpm, 0)}</span>
                        </div>
                      </TableCell>
                    )}

                    {/* XPM - 隐藏在大屏幕以下 */}
                    {visibleColumns.xpm && (
                      <TableCell className="text-center hidden lg:table-cell">
                        <div className="flex items-center justify-center gap-1">
                          <Zap className="w-3 h-3 text-muted-foreground" />
                          <span className="font-medium">{formatNumber(player.avg_xpm, 0)}</span>
                        </div>
                      </TableCell>
                    )}

                    {/* 位置评分 - 只在超大屏幕显示 */}
                    {visibleColumns.positionScore && (
                      <TableCell className="text-center hidden xl:table-cell">
                        <div className="flex items-center justify-center gap-1">
                          <span className="font-medium text-blue-600">{formatNumber(player.positionScore, 1)}</span>
                        </div>
                      </TableCell>
                    )}

                    {/* 平均数据 - 只在超大屏幕显示 */}
                    {visibleColumns.avgData && (
                      <TableCell className="text-center hidden xl:table-cell">
                        <div className="text-xs space-y-1">
                          <div>K/D/A: {formatNumber(player.avg_kills)}/{formatNumber(player.avg_deaths)}/{formatNumber(player.avg_assists)}</div>
                          <div className="text-muted-foreground">
                            补刀: {formatNumber(player.avg_last_hits, 0)} | 伤害: {formatNumber(player.avg_hero_damage, 0)}
                          </div>
                        </div>
                      </TableCell>
                    )}

                    {/* 最终评分 */}
                    {visibleColumns.score && (
                      <TableCell className="text-right">
                        <div className="text-lg font-bold text-primary">
                          {formatNumber(player.positionScore, 1)}
                        </div>
                        {/* 移动端显示额外信息 */}
                        <div className="text-xs text-muted-foreground lg:hidden">
                          <div>评分: {formatNumber(player.positionScore, 1)}</div>
                        </div>
                      </TableCell>
                    )}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </div>

        {/* 分页控制 */}
        <div className="flex items-center justify-between px-4 mt-4">
          <div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
            {selectedRows.size} of {getFilteredAndSortedPlayers.length} row(s) selected.
          </div>
          <div className="flex w-full items-center gap-8 lg:w-fit">
            <div className="hidden items-center gap-2 lg:flex">
              <label className="text-sm font-medium">Rows per page</label>
              <Select value={rowsPerPage.toString()} onValueChange={(value) => setRowsPerPage(Number(value))}>
                <SelectTrigger className="w-20">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="10">10</SelectItem>
                  <SelectItem value="20">20</SelectItem>
                  <SelectItem value="50">50</SelectItem>
                  <SelectItem value="100">100</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex w-fit items-center justify-center text-sm font-medium">
              Page {currentPage} of {getTotalPages()}
            </div>
            <div className="ml-auto flex items-center gap-2 lg:ml-0">
              <Button
                variant="outline"
                size="sm"
                className="hidden h-8 w-8 p-0 lg:flex"
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
              >
                <span className="sr-only">Go to first page</span>
                <ChevronsLeft className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="h-8 w-8 p-0"
                onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                disabled={currentPage === 1}
              >
                <span className="sr-only">Go to previous page</span>
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="h-8 w-8 p-0"
                onClick={() => setCurrentPage(prev => Math.min(getTotalPages(), prev + 1))}
                disabled={currentPage === getTotalPages()}
              >
                <span className="sr-only">Go to next page</span>
                <ChevronRight className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="hidden h-8 w-8 p-0 lg:flex"
                onClick={() => setCurrentPage(getTotalPages())}
                disabled={currentPage === getTotalPages()}
              >
                <span className="sr-only">Go to last page</span>
                <ChevronsRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

export default LeaguePlayerRanking